<template>
  <div class="address-page">
    <el-header class="header" height="70px">
      <div class="header-content">
        <div class="logo">
          <h1 @click="$router.push('/')" style="cursor: pointer;">周氏商城</h1>
        </div>
        <div class="nav-actions">
          <el-button @click="$router.push('/products')" type="primary" plain>
            继续购物
          </el-button>
          <template v-if="userStore.token">
            <el-dropdown @command="handleUserCommand">
              <el-button type="primary">
                {{ userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="main-content">
      <div class="page-header">
        <h2>收货地址管理</h2>
        <div class="page-actions">
          <el-button 
            v-if="isFromOrders" 
            type="primary" 
            @click="goBackToOrders"
          >
            返回订单
          </el-button>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item @click="$router.push('/')">首页</el-breadcrumb-item>
            <el-breadcrumb-item>收货地址</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>

      <!-- 地址列表 -->
      <div class="address-list" v-loading="loading">
        <el-card v-for="address in addresses" :key="address.id" class="address-card" shadow="hover">
          <div class="address-content">
            <div class="address-info">
              <div class="contact-info">
                <span class="contact-name">{{ address.contact }}</span>
                <span class="contact-phone">{{ address.mobile }}</span>
                <el-tag v-if="address.isDefault === 1" type="success" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ address.province }} {{ address.city }} {{ address.town }} {{ address.street }}
              </div>
              <div v-if="address.notes" class="address-notes">
                备注：{{ address.notes }}
              </div>
            </div>
            <div class="address-actions">
              <el-button 
                v-if="address.isDefault !== 1" 
                type="primary" 
                size="small" 
                @click="setDefaultAddress(address.id!)"
              >
                设为默认
              </el-button>
              <el-button type="primary" size="small" @click="editAddress(address)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteAddress(address.id!)">
                删除
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 新增地址卡片 -->
        <el-card class="address-card add-address-card" shadow="hover" @click="showAddressDialog()">
          <div class="add-address-content">
            <el-icon class="add-icon"><Plus /></el-icon>
            <span>新增收货地址</span>
          </div>
        </el-card>

        <el-empty v-if="!loading && addresses.length === 0" description="暂无收货地址">
          <el-button type="primary" @click="showAddressDialog()">新增地址</el-button>
        </el-empty>
      </div>
    </el-main>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="isEdit ? '编辑地址' : '新增地址'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="contact">
          <el-input v-model="addressForm.contact" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addressForm.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="所在地区" prop="areaCodes">
          <el-cascader
            v-model="addressForm.areaCodes"
            :options="areaOptions"
            :props="cascaderProps"
            placeholder="请选择所在地区"
            style="width: 100%"
            @change="handleAreaChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="street">
          <el-input
            v-model="addressForm.street"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="addressForm.notes" placeholder="请输入备注信息（可选）" />
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch v-model="addressForm.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="saveLoading">
            {{ isEdit ? '保存' : '新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { 
  getMyAddresses, 
  createAddress, 
  updateAddress, 
  deleteAddress as deleteAddressApi, 
  setDefaultAddress as setDefaultAddressApi 
} from '@/api/address'
import { getFullAreaData, getAreaName, findAreaCodesByName } from '@/utils/areaData'
import type { AddressDTO } from '@/api/address'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 检查是否来自订单页面
const isFromOrders = computed(() => {
  return route.query.from === 'orders'
})

// 响应式数据
const addresses = ref<AddressDTO[]>([])
const loading = ref(false)
const saveLoading = ref(false)
const addressDialogVisible = ref(false)
const isEdit = ref(false)
const addressFormRef = ref()

// 地区数据
const areaOptions = ref(getFullAreaData())

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

// 地址表单
const addressForm = ref<AddressDTO>({
  mobile: '',
  street: '',
  contact: '',
  isDefault: 0,
  notes: '',
  areaCodes: []
})

// 表单验证规则
const addressRules = {
  contact: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  areaCodes: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  street: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

// 返回订单页面
const goBackToOrders = () => {
  router.push('/orders?mode=checkout')
}

// 处理地区选择变化
const handleAreaChange = (value: string[]) => {
  if (value && value.length >= 3) {
    // 根据编码获取地区名称
    addressForm.value.province = getAreaName(value[0])
    addressForm.value.city = getAreaName(value[1])
    addressForm.value.town = getAreaName(value[2])
  }
}

// 显示地址对话框
const showAddressDialog = (address?: AddressDTO) => {
  isEdit.value = !!address
  if (address) {
    // 编辑模式：填充表单数据
    addressForm.value = { ...address }
    // 如果有地区信息，转换为areaCodes
    if (address.province && address.city && address.town) {
      addressForm.value.areaCodes = findAreaCodesByName(
        address.province,
        address.city,
        address.town
      )
    } else {
      addressForm.value.areaCodes = []
    }
  } else {
    // 新增模式：重置表单
    addressForm.value = {
      mobile: '',
      street: '',
      contact: '',
      isDefault: 0,
      notes: '',
      areaCodes: []
    }
  }
  addressDialogVisible.value = true
}

// 编辑地址
const editAddress = (address: AddressDTO) => {
  showAddressDialog(address)
}

// 保存地址
const saveAddress = async () => {
  try {
    await addressFormRef.value.validate()
    saveLoading.value = true

    // 确保地区信息已设置
    if (addressForm.value.areaCodes && addressForm.value.areaCodes.length >= 3) {
      handleAreaChange(addressForm.value.areaCodes)
    }

    if (isEdit.value) {
      // 更新地址
      await updateAddress(addressForm.value.id!, addressForm.value)
      ElMessage.success('地址更新成功')
    } else {
      // 新增地址
      await createAddress(addressForm.value)
      ElMessage.success('地址添加成功')
    }

    addressDialogVisible.value = false
    loadAddresses() // 重新加载地址列表
    
    // 如果来自订单页面，提示用户可以返回
    if (isFromOrders.value) {
      ElMessage.success('地址保存成功，您可以返回订单页面继续下单')
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败')
  } finally {
    saveLoading.value = false
  }
}

// 删除地址
const deleteAddress = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteAddressApi(id)
    ElMessage.success('地址删除成功')
    loadAddresses() // 重新加载地址列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }
}

// 设置默认地址
const setDefaultAddress = async (id: number) => {
  try {
    await setDefaultAddressApi(id)
    ElMessage.success('默认地址设置成功')
    loadAddresses() // 重新加载地址列表
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 加载地址列表
const loadAddresses = async () => {
  try {
    loading.value = true
    const response = await getMyAddresses()
    if (response.data && response.data.code === 200) {
      addresses.value = response.data.data || []
    } else {
      console.error('地址数据格式错误:', response)
      ElMessage.error('地址数据格式错误')
    }
  } catch (error) {
    console.error('加载地址列表失败:', error)
    ElMessage.error('加载地址列表失败')
  } finally {
    loading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  // 检查用户是否已登录
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  loadAddresses()
})
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo h1 {
  color: #409eff;
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.page-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.address-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.address-card:hover {
  transform: translateY(-2px);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.contact-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.contact-phone {
  color: #666;
}

.address-detail {
  color: #333;
  line-height: 1.5;
  margin-bottom: 5px;
}

.address-notes {
  color: #999;
  font-size: 12px;
}

.address-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.add-address-card {
  border: 2px dashed #ddd;
  background: #fafafa;
}

.add-address-card:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.add-address-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  color: #666;
}

.add-icon {
  font-size: 32px;
  margin-bottom: 10px;
  color: #999;
}

.add-address-card:hover .add-icon {
  color: #409eff;
}

/* 响应式 */
@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .address-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .address-actions {
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style> 